package quotation.web.quotationSys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import quotation.web.quotationSys.ddd.entity.QuotationSysEntity;
import quotation.web.quotationSys.ddd.form.AddQuotationSysForm;
import quotation.web.quotationSys.ddd.form.UpadateQuotationSysForm;
import quotation.web.quotationSys.ddd.vo.QuotationSysVo;
import quotation.web.quotationSys.mapper.QuotationSysMapper;
import quotation.web.quotationSys.service.QuotationSysService;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lyx
 * @date 2025/2/24
 */
@Slf4j
@Service
public class QuotationSysServiceImpl extends ServiceImpl<QuotationSysMapper, QuotationSysEntity> implements QuotationSysService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(AddQuotationSysForm form) {

        QuotationSysEntity quotationSysEntity = BeanUtil.copyProperties(form, QuotationSysEntity.class);

        this.save(quotationSysEntity);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(UpadateQuotationSysForm form) {
        QuotationSysEntity quotationSysEntity = BeanUtil.copyProperties(form, QuotationSysEntity.class);
        this.updateById(quotationSysEntity);
    }

    @Override
    public List<QuotationSysVo> getAll() {
        List<QuotationSysEntity> list = this.lambdaQuery()
                .orderByAsc(QuotationSysEntity::getName)
                .list();
        List<QuotationSysEntity> topList = list.stream()
                .filter(t -> t.getIsTop() == 1)
                .collect(Collectors.toList());

        List<QuotationSysVo> quotationSysVoList = topList.stream()
                .map(t -> {
                    QuotationSysVo quotationSysVo = BeanUtil.copyProperties(t, QuotationSysVo.class);
                    List<QuotationSysEntity> child = list.stream()
                            .filter(p -> Objects.equals(p.getParentId(), t.getId()))
                            .collect(Collectors.toList());
                    quotationSysVo.setChild(child);
                    return quotationSysVo;
                }).collect(Collectors.toList());

        return quotationSysVoList;

    }
}
